'''
Author: @zhyy
Date: 2021-01-31 11:03:09
LastEditors: @zhyy
LastEditTime: 2021-02-01 19:46:45
'''
from app import db
from sqlalchemy import desc, asc
from app.dao.base import BaseModel
from app.models.model import User
from app.models.model_schema import Userchema
from werkzeug.security import generate_password_hash, check_password_hash


class UserDB(User, BaseModel):
    def __init__(cls, classname, bases, dict_, **kw):
        super().__init__(classname, bases, dict_, **kw)
    
    @staticmethod
    def get_user_role(fild_list,filters,chema):
        data=db.session.query(fild_list).filter(*filters).all()
        data_schema = chema(many=True).dump(data)
        return  data_schema
    #设置密码
    @staticmethod
    def set_password(password):
        return generate_password_hash(password)

    #校验密码
    @staticmethod
    def check_password(hash_password, password):
        return check_password_hash(hash_password, password)

    #获取用户信息
    @staticmethod
    def get(self,filters):
        res = db.query(User).filter(*filters).first()
        if res == None:
            return None
        else:
            return res

    # 增加用户
    def add(self, user):
        db.add(user)
        db.commit()
        return True

    # 根据id删除用户
    def delete(self, id):
        self.query.filter_by(id=id).delete()
        return db.commit()

    # 更新更新时间
    @staticmethod
    def update(email, updated_at):
        db.session.query(User).filter_by(email=email).update({'updated_at': updated_at})
        return db.session.commit()
